package cn.com.yang.server.tomcat;

import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;
import org.springframework.boot.web.server.WebServerException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * 手写tomcat容器
 * @author yangyijin
 * @since 2023年6月15日-下午3:28:37
 */
public class TomcatContainer implements WebServer{

	@Override
	public void start(WebApplicationContext applicationContext) throws WebServerException {
		System.out.println("启动tomcat...");
		doStart(applicationContext);
	}

	@SuppressWarnings("static-access")
	private void doStart(WebApplicationContext applicationContext) {
		Tomcat tomcat = new Tomcat();
		Server server = tomcat.getServer();
		Service service = server.findService("Tomcat");
		Connector connector = new Connector();
		connector.setPort(8080);
		service.addConnector(connector);
		
		Engine engine = new StandardEngine();
		engine.setDefaultHost("localhost");
		Host host = new StandardHost();
		engine.addChild(host);
		service.setContainer(engine);
		
		String contextPath ="";
		Context context = new StandardContext();
		context.setPath(contextPath);
		context.addLifecycleListener(new Tomcat.FixContextListener());
		
		tomcat.addServlet(context,"dispatcher",new DispatcherServlet(applicationContext));
		context.addServletMappingDecoded("/*","dispatcher");
		
		try {
			tomcat.start();
		} catch (LifecycleException e) {
			e.printStackTrace();
		}
	}

}
